package io.xxx.eva.task;

import io.xxx.eva.task.request.AddTaskRequest;
import io.xxx.eva.task.request.GetTaskRequest;
import io.xxx.eva.task.request.UpdateTaskRequest;
import jakarta.annotation.Resource;
import org.quartz.SchedulerException;
import org.quartz.UnableToInterruptJobException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/tasks")
public class TaskController {

    @Resource
    private TaskService taskService;

    @PostMapping
    public long add(@RequestBody AddTaskRequest request) throws SchedulerException {
        return taskService.add(request);
    }

    @PutMapping("/{id:\\d+}")
    public void update(@PathVariable long id, @RequestBody UpdateTaskRequest request) {
        request.setId(id);
        taskService.update(request);
    }

    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable long id) throws SchedulerException {
        taskService.delete(id);
    }

    @GetMapping
    public Page<Task> list(GetTaskRequest request, @PageableDefault Pageable pageable) {
        return taskService.list(request, pageable);
    }

    @PutMapping("/{id:\\d+}")
    public void cancel(@PathVariable long id) throws UnableToInterruptJobException {
        taskService.cancel(id);
    }

    @GetMapping("/{id:\\d+}")
    public Optional<Task> get(@PathVariable long id) {
        return taskService.get(id);
    }
}
